//
//  AudioPlayer.m
//  LO_MUSIC
//
//  Created by 胡林 on 16/2/26.
//  Copyright © 2016年 杨少锋. All rights reserved.
//

#import "AudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
static AudioPlayer * audioPlayer = nil;
@interface AudioPlayer ()
//播放器
@property(nonatomic , strong)AVPlayer * locaPlayer;

@property(nonatomic,assign,getter=isCurrenIsPlaying)BOOL curremtIsPlaying;
@property(nonatomic,strong)NSTimer * timer;

@end
@implementation AudioPlayer

//是否正在播放(外部不能改变)重写的get方法
-(BOOL)isPlaying{
    return self.isCurrenIsPlaying;
}


#pragma mark -1. 文件是单例
+(instancetype)shareAudioPlayer{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        audioPlayer = [[AudioPlayer alloc] init];
    });
    return audioPlayer;
    
}


-(instancetype)init{
    self = [super init];
    if (self) {
      //接受avplayer播放完成的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }return self;
}
#pragma mark -接受播放接受的通知
-(void)playEnd{
    //播放结束
    if (self.delegate && [self.delegate respondsToSelector:@selector(playFinish)]) {
        [self.delegate playFinish];
    }
    
    
}




#pragma mark -2. 播放
-(void)plauWithurl:(NSString * )url{
    //移除监听状态n
    [self.locaPlayer.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    //创建一个播放对象
    AVPlayerItem * item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];
    //1.监听者 2.监听的属性  3.新值，旧值  4.附加信息
    [item addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
    //播放
    [self.locaPlayer replaceCurrentItemWithPlayerItem:item];
//    self.curremtIsPlaying = YES;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    //如果监听的属性不是status，直接返回
    if (![keyPath isEqualToString:@"status"]) {
        return;
    }
    //取出变化的值
    AVPlayerItemStatus value = [change[@"new"]integerValue];
    if (value == AVPlayerItemStatusReadyToPlay) {
        //准备好了
        [self play];
    }else{
        //准备失败 准备情况不知道
    }
}


#pragma mark -3. 暂停/恢复
-(void)playOrPause
{
    //判断是否正在播放
    if (self.isPlaying) {
        //暂停
        [self pause];
    }else{
         //播放
        [self play];

    }
}
#pragma mark 把暂停和播放抽成方法
//播放
-(void)play{
 //
    //播放
    [self.locaPlayer play];
    self.curremtIsPlaying = YES;
    if (self.timer) {
        return;
    }
    //进度条
    //repeats Yes没0.1秒执行一次 No只执行一次
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}
//暂停
-(void)pause{
    [self.locaPlayer pause];
    self.curremtIsPlaying = NO;
    //清空timer
    [self.timer invalidate];
    self.timer = nil;
}



-(void)timerAction{
    if (self.delegate && [self.delegate respondsToSelector:@selector(playWithTime:)]) {
        CGFloat time = self.locaPlayer.currentTime.value * 1.0 / self.locaPlayer.currentTime.timescale;
        [self.delegate playWithTime:time];
    }
}
#pragma mark - 4. 停止
-(void)stop{
    //把时间设置为0
   [ self.locaPlayer seekToTime:CMTimeMakeWithSeconds(0, self.locaPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            //设置完毕
            [self pause];//暂停
            self.curremtIsPlaying = NO;//标记当前的播放状态
        }
   }];
    //暂停播放
    //当前的播放状态为NO
}

#pragma mark -5. 从什么时候开始播放
-(void)seekoWithTime:(CGFloat)time{
    //先暂停
    [self pause];
    //设置从什么时候开始播放
    [self.locaPlayer seekToTime:CMTimeMakeWithSeconds(time, self.locaPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            [self play];
        }
    }];
    //播放
}

#pragma mark -获取音量
-(CGFloat)volume{
    return self.locaPlayer.volume;
}


#pragma mark -设置音量
-(void)setVolume:(CGFloat)volume{
    self.locaPlayer.volume = volume;
}

#pragma mark -懒加载
-(AVPlayer *)locaPlayer{
    if (!_locaPlayer) {
        _locaPlayer = [[AVPlayer alloc] init];
        _locaPlayer.volume = 0.5;//初始化音量
    }return _locaPlayer;
}

@end
